import * as crypto from "crypto";

//定义一个块类
class Block {
  readonly hash: string; //该块的hash

  constructor(
    readonly index: number, //该块的索引
    readonly previousHash: string, //前一个块的hash
    readonly timestamp: number, //时间戳
    readonly data: string //应用数据
  ) {
    this.hash = this.calculateHash();
  }

  private calculateHash(): string {
    const data = `${this.index}${this.previousHash}${this.timestamp}${this.data}`;
    return crypto.createHash("sha256").update(data).digest("hex");
  }
}

//定义一个区块链类
class Blockchain {
  private readonly chain: Block[] = []; //链

  //获取最近添加的块引用的getter
  private get latestBlock(): Block {
    return this.chain[this.chain.length - 1];
  }

  //构造函数，创建创世区块并添加到链中
  constructor() {
    this.chain.push(new Block(0, "0", Date.now(), "Genesis Block"));
  }

  //创建新块实例
  addBlock(data: string): void {
    const block = new Block(
      this.latestBlock.index + 1,
      this.latestBlock.hash,
      Date.now(),
      data
    );
    this.chain.push(block);
  }
}

//创建三区块的链
console.log("创建创世区块");
const blockchain = new Blockchain();

console.log("创建第一区块");
blockchain.addBlock("Block 1");

console.log("创建第二区块");
blockchain.addBlock("Block 2");

console.log(JSON.stringify(blockchain, null, 2)); //打印链